package cn.tedu.sp06.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import web.util.JsonResult;

import javax.servlet.http.HttpServletRequest;

@Component
public class AccessFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    public int filterOrder() {
        return 6;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext currentContext = RequestContext.getCurrentContext();
        String serviceId = (String) currentContext.get("serviceId");
        if("order-service".equals(serviceId)){
            return true;
        }
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            currentContext.setSendZuulResponse(false);
            String jsonString = JsonResult.build().code(JsonResult.NOT_LOGIN).msg("未能在请求中发现token，请先登陆").toString();
            currentContext.addZuulResponseHeader("Content-Type","application/json;charset=utf-8");
            currentContext.setResponseBody(jsonString);
        }
        return null;
    }
}
